package com.liwei.lwmail.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.liwei.common.to.SkuHasStockVo;
import com.liwei.common.utils.R;
import com.liwei.lwmail.product.entity.SkuImagesEntity;
import com.liwei.lwmail.product.entity.SpuInfoDescEntity;
import com.liwei.lwmail.product.feign.WareFeignService;
import com.liwei.lwmail.product.service.*;
import com.liwei.lwmail.product.vo.SkuItemSaleAttrVo;
import com.liwei.lwmail.product.vo.SkuItemVo;
import com.liwei.lwmail.product.vo.SpuItemAttrGroupVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liwei.common.utils.PageUtils;
import com.liwei.common.utils.Query;

import com.liwei.lwmail.product.dao.SkuInfoDao;
import com.liwei.lwmail.product.entity.SkuInfoEntity;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService imagesService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        /**
         * key
           catelogId
           brandId
           min
           max
         */
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<SkuInfoEntity>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("sku_id",key).or().like("sku_name",key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)){
            wrapper.eq("brand_id",catelogId);
        }
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min) && !"0".equals(min)){
            wrapper.ge("price",min);
        }
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max) && !"0".equals(max)){
            wrapper.le("price",max);
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        return this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();

        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            //1、sku基本信息pms_sku_info
            SkuInfoEntity info = getById(skuId);
            skuItemVo.setInfo(info);
            return info;
        }, executor);

        CompletableFuture<Void> attrsFuture = infoFuture.thenAcceptAsync((result) -> {
            //4、sku所属spu的销售属性组合
            List<SkuItemSaleAttrVo> saleAttrs = skuSaleAttrValueService.getSaleAttrsBySpuId(result.getSpuId());
            skuItemVo.setSaleAttrs(saleAttrs);
        }, executor);

        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((result) -> {
            //5、sku所属spu的介绍pms_sku_info_desc
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(result.getSpuId());
            skuItemVo.setDesc(spuInfoDescEntity);
        }, executor);

        CompletableFuture<Void> groupAttrFuture = infoFuture.thenAcceptAsync((result) -> {
            //6、spu的规格参数
            List<SpuItemAttrGroupVo> groupAttrs = attrGroupService.getAttrGroupWithAttrsBySpuId(result.getSpuId(), result.getCatalogId());
            skuItemVo.setGroupAttrs(groupAttrs);
        }, executor);


        CompletableFuture<Void> hasStockFuture = CompletableFuture.runAsync(() -> {
            //2、调用远程服务查询sku库存
            R r = wareFeignService.getSkusHasStock(Arrays.asList(skuId));
            if (r.getCode() == 0) {
                List<SkuHasStockVo> data = r.getData("data", new TypeReference<List<SkuHasStockVo>>() {
                });
                skuItemVo.setHasStock(data.get(0).getHasStock());
            } else {
                skuItemVo.setHasStock(false);
            }
        }, executor);

        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            //3、sku图片信息pms_sku_images
            List<SkuImagesEntity> images = imagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(images);
        }, executor);

        //get方法阻塞等待所有任务完成
        CompletableFuture.allOf(attrsFuture,descFuture,groupAttrFuture,hasStockFuture,imagesFuture).get();

        return skuItemVo;
    }

}